package com.zdwhong.mysqlms.multidatasource;

import lombok.extern.slf4j.Slf4j;

/**
 * @author ZDW
 * @since 2021-05-25 18:54
 * 数据源管理类
 */
@Slf4j
public class DBContextHolder {

    /**
     * 外部一个请求将会产生一个线程与之对应，每个线程的变量可用ThreadLocal进行存储
     */
    private static final ThreadLocal<DBTypeEnum> CONTEXT_HOLDER = new ThreadLocal<>();

    public static void set(DBTypeEnum dbType) {
        CONTEXT_HOLDER.set(dbType);
    }

    public static DBTypeEnum get() {
        return CONTEXT_HOLDER.get();
    }

    public static void master() {
        set(DBTypeEnum.MASTER);
        log.info("切换到master");
    }

    public static void slave() {
        set(DBTypeEnum.SLAVE);
        log.info("切换到slave");
    }

    public static void cleanAll() {
        /**
         * ThreadLocal使用完要remove，防止内存泄漏
         */
        CONTEXT_HOLDER.remove();
        log.info("清空线程");
    }
}
